package com.lss.loginregister;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.lss.loginregister.activity.HomeActivity;
import com.lss.loginregister.activity.RegisterActivity;
import com.lss.loginregister.util.DatabaseHelper;
import com.lss.loginregister.util.PrefsUtil;

import java.util.Objects;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private TextInputEditText loginPwd;
    private TextView loginUser;
    private DatabaseHelper databaseHelper;
    private ImageView visibilityIcon;
    private boolean isPasswordVisible = false;
    private CheckBox cbRemember;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 如果是过期检查触发的跳转，直接结束
        if (getIntent().getBooleanExtra("from_expired_check", false)) {
            finish();
            return;
        }

        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        findViewById(R.id.btn_login_login).setOnClickListener(this);
        loginPwd = findViewById(R.id.tied_login_pwd);
        loginUser = findViewById(R.id.tied_login_user);
        TextView tvRegister = findViewById(R.id.tv_register);
        tvRegister.setOnClickListener(v -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        });
        // 初始化 DatabaseHelper 对象
        databaseHelper = new DatabaseHelper(this);

        tvRegister.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                v.setAlpha(0.7f);
            } else {
                v.setAlpha(1.0f);
            }
            return false;
        });
        cbRemember = findViewById(R.id.cb_remember);

        // 自动填充已保存的账号密码
        String[] credentials = PrefsUtil.getCredentials(this);
        if (!credentials[0].isEmpty()) {
            loginUser.setText(credentials[0]);
            loginPwd.setText(credentials[1]);
            cbRemember.setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_login_login) {
            String pwdStr = loginPwd.getText().toString().trim();
            String userStr = loginUser.getText().toString().trim();
            DatabaseHelper.User user = databaseHelper.getUserByUsername(userStr);
            if (!pwdStr.isEmpty() && !userStr.isEmpty()) {
                String info = "账户：" + userStr + "\n" + "密码：" + pwdStr;
                useSnackbar(info);
            } else {
                useToast("请收入账户或密码！", Toast.LENGTH_SHORT);
                return;
            }
            if (user != null && Objects.equals(user.getUsername(), userStr) && Objects.equals(pwdStr, user.getPassword())) {
                if (cbRemember.isChecked()) {
                    PrefsUtil.saveCredentials(this, userStr, pwdStr);
                } else {
                    PrefsUtil.clearCredentials(this);
                }
                String info = "账户：" + userStr + "\n" + "密码：" + pwdStr;
                useSnackbar(info);
                Intent intent = new Intent(this, HomeActivity.class);
                // 传递用户数据
                intent.putExtra("user_id", user.getId());
                intent.putExtra("username", user.getUsername());
                intent.putExtra("password", user.getPassword());
                intent.putExtra("phone", user.getPhone());
                intent.putExtra("email", user.getEmail());
                startActivity(intent);
            } else {
                if (user == null) {
                    useToast("账户不存在，请注册！", Toast.LENGTH_SHORT);
                }
                if (user != null) {
                    useToast("账户或密码错误！", Toast.LENGTH_SHORT);
                }
            }

        }
    }

    private void useSnackbar(String info) {
        ConstraintLayout rootLayout = findViewById(R.id.main); // 根布局仍然是 ConstraintLayout
        Snackbar snackbar = Snackbar.make(rootLayout, info, Snackbar.LENGTH_SHORT);

        // 获取 Snackbar 的布局
        View snackbarView = snackbar.getView();

        // 修改布局参数
        ViewGroup.LayoutParams layoutParams = snackbarView.getLayoutParams();
        if (layoutParams instanceof FrameLayout.LayoutParams) {
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) layoutParams;
            params.gravity = Gravity.BOTTOM; // 设置 Snackbar 显示在底部
            snackbarView.setLayoutParams(params);
        }

        // 显示 Snackbar
        snackbar.show();
    }

    private void useToast(String str, int LongOrShort) {
        Toast.makeText(this, str, LongOrShort).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isPasswordVisible) {
            loginPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            visibilityIcon.setImageResource(R.drawable.ic_visibility_off);
            isPasswordVisible = false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 延迟检查避免阻塞UI
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (PrefsUtil.isLoginExpired(this)) {
                PrefsUtil.clearCredentials(this);

                // 获取当前栈顶的Activity类名
                String currentClassName = getClass().getName();

                // 如果当前已经是 LoginActivity，则不重复启动
                if (!currentClassName.equals(LoginActivity.class.getName())) {
                    startActivity(new Intent(this, LoginActivity.class)
                            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)
                            .putExtra("from_expired_check", true));
                    finish();
                }
            }
        }, 500);
    }
}